using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using sbMembership.Library.Domain;
using sbMembership.Library.Presenters.ViewInterfaces;

namespace sbMembership.Library.Presenters
{
    public class EditRoleEventArgs : EventArgs
    {
        private string roleName;

        public string RoleName
        {
            get { return roleName; }
            set { roleName = value; }
        }
    }

    public class EditRolePresenter
    {
        private IEditRoleView view;
        public enum ActionEnum
        {
            added
            ,
            deleted
          , none
        }

        public EditRolePresenter(IEditRoleView view)
        {
            if (view == null) throw new ArgumentNullException("view may not be null");
            this.view = view;
        }

        public EventHandler EditRoleCompleteEvent;

        public void InitViewFor(string roleName)
        {
            DisplayMessageFor(ActionEnum.none);
            view.AvailableUsers = Membership.GetAllUsers();
            view.RoleToEdit = roleName;
            view.UsersInRole = Roles.GetUsersInRole(roleName);
        }

        private void DisplayMessageFor(ActionEnum action)
        {
            if (action == ActionEnum.added)
                view.Message = "The role was successfully assigned.";
            else if (action == ActionEnum.deleted)
                view.Message = "The role was successfully removed.";
            else
                view.Message = "Use this form to add a new role.";
        }

        public void AssignUser(string userName)
        {
            Roles.AddUserToRole(userName, view.RoleToEdit);
            DisplayMessageFor(ActionEnum.added);
            view.UsersInRole = Roles.GetUsersInRole(view.RoleToEdit);
            EditRoleCompleteEvent(this, null);
        }

        public void RemoveUser(string userName)
        {
            Roles.RemoveUserFromRole(userName, view.RoleToEdit);
            DisplayMessageFor(ActionEnum.deleted);
            view.UsersInRole = Roles.GetUsersInRole(view.RoleToEdit);
            EditRoleCompleteEvent(this, null);
        }
    }
}
